<?php


namespace Modules\Admin\Http\Controllers\Authorization\Role;


use Modules\Common\General\Security\Authorization\Manager;
use Modules\Common\Models\AdminRole;
use Modules\Common\Util\Api;

class Retrieve
{
    /**
     * @Route(path=/api/admin/authorization/role)
     */
    public function retrieve()
    {
        $roles = AdminRole::orderBy('sort')->get(['id', 'name', 'created_at', 'sort']);
        $m = new Manager();
        $roles->each(function ($role) use ($m) {
            $ownRolesCount = count($m->getRolesForRole($role->id));
            $allRolesCount = count($m->getImplicitRolesForRole($role->id));
            $ownPermissionsCount = count($m->getPermissionsForRole($role->id));
            $allPermissionsCount = count($m->getImplicitPermissionsForRole($role->id));

            $role->own_roles = $ownRolesCount;
            $role->all_roles = $allRolesCount;
            $role->own_permissions = $ownPermissionsCount;
            $role->all_permissions = $allPermissionsCount;
        });
        return Api::success($roles);
    }

    /**
     * @Route(path=/api/admin/authorization/role/{role_id})
     */
    public function retrieveOne(int $roleId)
    {
        $role = AdminRole::find($roleId, ['id', 'name', 'created_at', 'sort']);
        $m = new Manager();
        $role->permissions = $m->getPermissionsForRoleForPresentation($roleId);
        $role->hierarchy = $m->getRoleHierarchyForRoleWithPermission($role->id);
        return Api::success($role);
    }


}
